package com.jtech.together.view.activity;

import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.jtech.together.R;
import com.jtech.together.model.UserModel;
import com.jtech.together.mvp.contract.RegisterContract;
import com.jtech.together.mvp.presenter.RegisterPresenter;
import com.jtech.together.util.ActivityJump;
import com.jtech.together.util.MD5;
import com.jtech.together.view.activity.base.BaseActivity;
import com.jtech.together.view.weight.dialog.CustomProgressDialog;
import com.umeng.analytics.MobclickAgent;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 注册页面
 * Created by wuxubaiyang on 2017/5/10.
 */
public class RegisterActivity extends BaseActivity implements RegisterContract.View, Toolbar.OnMenuItemClickListener,
        TextView.OnEditorActionListener {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.textinputlayout_register_username)
    TextInputLayout textInputLayoutUserName;
    @Bind(R.id.textinputlayout_register_password)
    TextInputLayout textInputLayoutPassword;
    @Bind(R.id.textinputlayout_register_password_confirm)
    TextInputLayout textInputLayoutPasswordConfirm;
    @Bind(R.id.content)
    CoordinatorLayout content;

    private RegisterContract.Presenter presenter;

    @Override
    protected void initVariables(Bundle bundle) {
        //绑定P类
        presenter = new RegisterPresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_register);
        //设置标题栏
        setSupportActionBar(toolbar);
        //设置标题栏菜单点击事件
        toolbar.setOnMenuItemClickListener(this);
        //设置输入监听
        textInputLayoutUserName.getEditText()
                .addTextChangedListener(new OnTextChangeListener(textInputLayoutUserName));
        textInputLayoutPassword.getEditText()
                .addTextChangedListener(new OnTextChangeListener(textInputLayoutPassword));
        textInputLayoutPasswordConfirm.getEditText()
                .addTextChangedListener(new OnTextChangeListener(textInputLayoutPasswordConfirm));
        //设置键盘动作监听
        textInputLayoutPasswordConfirm.getEditText()
                .setOnEditorActionListener(this);
    }

    @Override
    protected void loadData() {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        toolbar.inflateMenu(R.menu.menu_done);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 提交注册
     *
     * @return
     */
    private boolean submit() {
        //判断用户名是否为空
        String username = textInputLayoutUserName.getEditText()
                .getText().toString();
        if (TextUtils.isEmpty(username)) {
            textInputLayoutUserName.setError("用户名不能为空");
            return false;
        }
        //判断密码是否为空
        String password = textInputLayoutPassword.getEditText()
                .getText().toString();
        if (TextUtils.isEmpty(password)) {
            textInputLayoutPassword.setError("密码不能为空");
            return false;
        }
        //判断密码长度是否大于等于8
        if (password.length() < 8) {
            textInputLayoutPassword.setError("密码至少8位");
            return false;
        }
        //判断确认密码是否为空
        String passwordConfirm = textInputLayoutPasswordConfirm.getEditText()
                .getText().toString();
        if (TextUtils.isEmpty(passwordConfirm)) {
            textInputLayoutPasswordConfirm.setError("确认密码不能为空");
            return false;
        }
        //用户名只允许英文以及数字
        String regEx = "^[a-zA-Z][a-zA-Z0-9_]{0,15}$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(username);
        if (!matcher.matches()) {
            textInputLayoutUserName.setError("只能使用字母或数字");
            return false;
        }
        //判断确认密码长度是否大于等于8
        if (passwordConfirm.length() < 8) {
            textInputLayoutPasswordConfirm.setError("密码至少8位");
            return false;
        }
        //判断两次输入是否一致
        if (!password.equals(passwordConfirm)) {
            textInputLayoutPassword.setError("两次密码输入不一致");
            textInputLayoutPasswordConfirm.setError("两次密码输入不一致");
            return false;
        }
        //提交注册
        presenter.register(username, MD5.to(password));
        CustomProgressDialog.showProgressDialog(getActivity(), "正在注册");
        return true;
    }

    @Override
    public void registerSuccess(UserModel userModel) {
        CustomProgressDialog.dismissProgressDialog();
        ActivityJump.build(getActivity(), ProfileCompleteActivity.class)
                .jump();
        onBackPressed();
    }

    @Override
    public void registerFail(String error) {
        CustomProgressDialog.dismissProgressDialog();
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done://完成
                return submit();
        }
        return false;
    }

    /**
     * 切换到登录
     */
    @OnClick(R.id.imagebutton_register_switch)
    public void onSwitch() {
        ActivityJump.build(getActivity(), LoginActivity.class)
                .jump();
        onBackPressed();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            return submit();
        }
        return false;
    }

    /**
     * 当输入变化的时候
     */
    private class OnTextChangeListener implements TextWatcher {
        private TextInputLayout textInputLayout;

        public OnTextChangeListener(TextInputLayout textInputLayout) {
            this.textInputLayout = textInputLayout;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //清空错误
            if (!TextUtils.isEmpty(textInputLayout.getError())) {
                textInputLayout.setError("");
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(this);
    }
}